package com.xjm.ips.controller.system.basic;

import com.xjm.ips.entity.AjaxJson;
import com.xjm.ips.entity.Menu;
import com.xjm.ips.entity.Role;
import com.xjm.ips.service.MenuRoleService;
import com.xjm.ips.service.MenuService;
import com.xjm.ips.service.RedisService;
import com.xjm.ips.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/system/basic/per")
public class PermissionController {
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    MenuRoleService menuRoleService;
    @Autowired
    RedisService redisService;

    @GetMapping("/")
    public List<Role> getAllRoles(){
        return roleService.getAllRoles();
    }

    @GetMapping("/getallmenus")
    public List<Menu> getAllMenus(){
        return menuService.getAllMenus();
    }

    @GetMapping("/getMidsByRoleIds/{roleId}")
    public List<Integer> getMidsByRoleId(@PathVariable Integer roleId){
        return menuService.getMidsByRoleId(roleId);
    }

    @PutMapping("/")
    public AjaxJson updateMenuRoLe(Integer rid,Integer[] menuIds){
        if(menuRoleService.updateMenuRoLe(rid,menuIds)){
            updateRedisMenuWithRole();
            return AjaxJson.ok("更新成功!");
        }
        return  AjaxJson.error("更新失败!");
    }

    @PostMapping("/role")
    public AjaxJson addRole(@RequestBody Role role){
        if(roleService.addRole(role)==1){
            updateRedisMenuWithRole();
            return AjaxJson.ok("添加成功!");
        }
        return AjaxJson.error("添加失败!");
    }

    @DeleteMapping("/role/{rid}")
    public AjaxJson deleteRoleById(@PathVariable Integer rid){
        if(roleService.deleteRoleById(rid)==1){
            updateRedisMenuWithRole();
            return AjaxJson.ok("删除成功!");
        }
        return AjaxJson.error("删除失败!");
    }

    /**
     * 当权限结构发生改变时，更新redis的权限菜单
     */
    private void updateRedisMenuWithRole(){
        List<Menu> menuList = menuService.getAllMenusWithRole();
        redisService.set("menuWithRole", menuList);
    }
}
